//
//  AccessTokenModel.swift
//  Checked
//
//  Created by Shinolr on 1/4/19.
//  Copyright © 2019 shinolr_go. All rights reserved.
//

import Foundation

struct AccessTokenModel: Decodable, SaveTokenProtocol {
    static var currentAccessToken: String? {
//        let uf = UserDefaults.standard
//        return uf.object(forKey: "accessToken") as? String
        if let cookies = HTTPCookieStorage.shared.cookies {
            for cookie in cookies where cookie.name == "accessToken" {
                return cookie.value
            }
        }
//        guard let cookies = HTTPCookieStorage.shared.cookies else {
//            return nil
//        }
//        for cookie in cookies {
//            if cookie.name == "accessToken" {
//                return cookie.value
//            }
//        }
        return nil
    }

    func saveAccessToken(_ completionHandler: (() -> Void)?) {
//        let uf = UserDefaults.standard
//        uf.set(accessToken!, forKey: "accessToken")
//        uf.synchronize()

        let cookiePropertites: [HTTPCookiePropertyKey: Any] = [HTTPCookiePropertyKey.name: "accessToken",
                                                               HTTPCookiePropertyKey.value: accessToken!,
                                                               HTTPCookiePropertyKey.path: "/",
                                                               HTTPCookiePropertyKey.expires: Date(timeIntervalSinceNow: 3600),
//                                                               HTTPCookiePropertyKey.domain: "https://api.trakt.tv",
                                                               HTTPCookiePropertyKey.originURL: "https://api.trakt.tv"
        ]
        let httpCookie = HTTPCookie(properties: cookiePropertites)
        HTTPCookieStorage.shared.setCookie(httpCookie!)
        completionHandler?()
    }

    var accessToken: String?
    var tokenType: String?
    var expiresIn: Int?
    var refreshToken: String?
    var scope: String?
    var createdAt: Int?

    private enum CodingKeys: String, CodingKey {
        case accessToken = "access_token"
        case tokenType = "token_type"
        case expiresIn = "expires_in"
        case refreshToken = "refresh_token"
        case scope
        case createdAt = "created_at"
    }
}

protocol SaveTokenProtocol {
    func saveAccessToken(_ completionHandler: (() -> Void)?)
    static var currentAccessToken: String? { get }
}
